package basics.classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author jiangwz
 * @create 2019/10/16.
 */
public class JwzClassLoader extends ClassLoader {

    private String path;

    public JwzClassLoader(String path) {
        this.path = path;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 加载类数据
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) {
        name = name.substring(name.lastIndexOf(".") + 1, name.length());
        name = path + name + ".class";
        System.err.println(name);
        InputStream is = null;
        ByteArrayOutputStream out = null;
        try {
            is = new FileInputStream(new File(name));
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int i = 0;
            while ((i = is.read(buffer)) != -1) {
                out.write(buffer, 0 , i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return out.toByteArray();
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String path= "D:\\ideaworkspace\\test-project\\java";
        JwzClassLoader jwzClassLoader = new JwzClassLoader(path+"\\");
        Class<?> c = jwzClassLoader.loadClass("basics.classloader.Hello");
        System.out.println("classLoader -> "+c.getClassLoader());
        Object o = c.newInstance();
        System.out.println(o);
    }


}
